package com.hippo.core.vm

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hippo.core.core.UserManger
import com.hippo.core.core.ext.toJson
import com.hippo.core.respository.ApiRepository
import com.hippo.core.respository.ApiRepository.changeAvatar
import com.hippo.core.state.MineState
import kotlinx.coroutines.launch

class MineVM : ViewModel() {


    var uiState by mutableStateOf(MineState())


    init {
        viewModelScope.launch {
            val userInfo = UserManger.getUserInfo()
            Log.i("MineVM", userInfo.toJson())
            uiState = uiState.copy(
                userInfo = userInfo,
            )
        }

    }


    fun updateState(state: MineState){
        uiState = state
    }


    fun getUserInfo() {
        viewModelScope.launch {
            ApiRepository.getUserInfo()
                .onSuccess {
                    uiState = uiState.copy(
                        userInfo = it,
                        isLoading = false,
                    )
                    UserManger.saveUserInfo(it)
                }
        }
    }


    fun updateNickName(nickName: String) {
        viewModelScope.launch {
            ApiRepository.changeNickName(nickName)
                .onSuccess {

                    // 更新用户信息
                    val userInfo = UserManger.getUserInfo()?.copy(nickName = nickName)
                    UserManger.saveUserInfo(userInfo)

                    // 更新UI
                    uiState = uiState.copy(
                        userInfo = userInfo,
                        isLoading = false,
                    )
                }
        }
    }

    fun updateAvatar(localImage: String) {
        viewModelScope.launch {
            ApiRepository
                .setFileUpload(localImage)
                .then {
                    changeAvatar(it.orEmpty())
                }
                .handleFailure()
                .onSuccess {

                    // 更新用户信息
                    val userInfo = UserManger.getUserInfo()?.copy(avatar = localImage)
                    UserManger.saveUserInfo(userInfo)

                    // 更新UI
                    uiState = uiState.copy(
                        userInfo = userInfo,
                        isLoading = false,
                    )
                }
        }
    }

}